package org.blaznyoght.subtitles.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import org.blaznyoght.subtitles.model.Collection;
import org.blaznyoght.subtitles.model.Parser;

public class OpenActionListener implements ActionListener {
	SwingApplication application;
	
	public OpenActionListener(SwingApplication application) {
		this.application = application;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		JFileChooser chooser = new JFileChooser();
		FileFilter filter = new FileFilter() {
			@Override
			public boolean accept(File file) {
				String name = file.getName();
				String ext = name.split("\\.")[name.split("\\.").length - 1];
				return ext.equalsIgnoreCase("srt");
			}

			@Override
			public String getDescription() {
				return "*.srt";
			}

		};
		chooser.setFileFilter(filter);
		int returnVal = chooser.showOpenDialog(application.getFrame());
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File subFile = chooser.getSelectedFile();
//			try {
				Parser parser = new Parser(subFile);
				Collection subtitles = parser.getCollection();
				subtitles.setFile(subFile);
				application.setSubtitles(subtitles);
				application.getFrame().setTitle(subFile.getName());
//			} catch (FileNotFoundException e1) {
//				final JDialog dialog = new JDialog();
//				dialog.setTitle("File not found !");
//				dialog.getContentPane().add(
//						new JLabel("File not found"));
//				JButton okButton = new JButton("Ok");
//				okButton.addActionListener(new ActionListener() {
//					public void actionPerformed(ActionEvent e) {
//						dialog.dispose();
//					}
//				});
//				dialog.getContentPane().add(okButton);
//				dialog.setVisible(true);
//			}
		}	
	}
}
